{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# 动态创建类"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## type用法\n",
    "type() 函数的语法格式有 2 种，分别如下：\n",
    "> type(obj)\n",
    "> type(name, bases, dict)\n",
    "\n",
    "以上这 2 种语法格式，各参数的含义及功能分别是：\n",
    "* 第一种语法格式用来查看某个变量（类对象）的具体类型，obj 表示某个变量或者类对象。\n",
    "* 第二种语法格式用来创建类，其中 name 表示类的名称；bases 表示一个元组，其中存储的是该类的父类；dict 表示一个字典，用于表示类内定义的属性或者方法。"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "使用type()函数查看变量或类对象的类型"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'float'>\n",
      "<class 'str'>\n",
      "<class 'int'>\n",
      "<class 'dict'>\n",
      "<class '__main__.Classmates'>\n"
     ]
    }
   ],
   "source": [
    "# 查看3.4的类型\n",
    "print(type(3.4))\n",
    "print(type('hello'))\n",
    "print(type(1992))\n",
    "print(type({}))\n",
    "# 查看类对象的类型\n",
    "class Classmates(object):\n",
    "    pass\n",
    "classmates = Classmates()\n",
    "print(type(classmates))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "使用type()创建类"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello,world  pangyazhou\n",
      "pangyazhou\n"
     ]
    }
   ],
   "source": [
    "# 定义一个实例方法\n",
    "def say(self):\n",
    "    print(\"hello,world \", self.name)\n",
    "\n",
    "# 使用type()函数创建类Person\n",
    "Person = type(\"Person\", (object,), dict(say=say, name='pangyazhou'))\n",
    "\n",
    "person = Person()\n",
    "person.say()\n",
    "print(person.name)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}